package club.itstudio.IContainer.service;

import club.itstudio.IContainer.entity.StudentCourse;
import club.itstudio.IContainer.entity.StudentCourseApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Service
public class StudentCourseService {
    private JdbcTemplate jdbcTemplate;
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private StudentCourseMapper studentCourseMapper = new StudentCourseMapper();

    @Autowired
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public boolean insert(StudentCourse studentCourse) {
        String sql = "insert into student_course(user_id, course_id) values(?, ?)";
        try {
            return jdbcTemplate.update(sql, studentCourse.userID, studentCourse.courseID) == 1;
        }catch (DataAccessException e) {
            logger.error("error insert into new student course", e);
            return false;
        }
    }

    public List<StudentCourse> getByUserID(int userID) {
        String sql = "select * from student_course where user_id=?";
        return jdbcTemplate.query(sql, studentCourseMapper, userID);
    }

    public List<StudentCourse> getByUserIDAndPage(int userID, int currentPage, int pageSize) {
        String sql = "select * from student_course where user_id=? order by id limit ?,?";
        return jdbcTemplate.query(sql, studentCourseMapper, userID, (currentPage - 1) * pageSize, pageSize);
    }

    public List<StudentCourse> getByCourseID(int courseID) {
        String sql = "select * from student_course where course_id=?";
        return jdbcTemplate.query(sql, studentCourseMapper, courseID);
    }

    public StudentCourse getByUserIDAndCourseID(int userID, int courseID) {
        String sql = "select * from student_course where user_id=? and course_id=?";
        StudentCourse studentCourse = null;
        try {
            studentCourse = jdbcTemplate.queryForObject(sql, studentCourseMapper, userID, courseID);
        }catch (DataAccessException e) {
            logger.error("error get student course by user id:" + userID + ", course id:" + courseID);
        }
        return studentCourse;
    }
}

class StudentCourseMapper implements RowMapper<StudentCourse> {
    @Override
    public StudentCourse mapRow(ResultSet resultSet, int i) throws SQLException {
        StudentCourse studentCourse = new StudentCourse();
        studentCourse.id = resultSet.getInt("id");
        studentCourse.userID = resultSet.getInt("user_id");
        studentCourse.courseID = resultSet.getInt("course_id");
        return studentCourse;
    }
}
